﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using MahApps.Metro.Controls;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor.GraphicDemonstrator
{
    public class DemoResourceCard : MetroWindow
    {
        public DemoResourceCard(GraphicDemonstrator demoWin, DemoResourceButton masterResourceButton)
        {
            this.ShowMinButton = false;

            this.Height = 400;
            this.Width = 500;
            this.WindowStyle = WindowStyle.ToolWindow;   // 注意：不能用普通窗口，否则最小化时易出问题。

            this.Owner = demoWin;
            this.masterResourceButton = masterResourceButton;

            try
            {
                var path = MasterResourceButton.ResourceInfo.AbsolutePath.ToLower();
                var htmlpath = "";
                if (path.EndsWith(".html"))
                {
                    htmlpath = path;
                }
                else if (path.EndsWith(".md"))
                {
                    htmlpath = path.Substring(0, path.Length - 3) + ".html";
                }
                else
                {
                    htmlpath = path;
                }

                if (htmlpath.EndsWith(".html"))
                {
                    if (System.IO.File.Exists(htmlpath))
                    {
                        this.frame = new Frame();
                        frame.Source = new Uri("file:///" + htmlpath);
                        this.Content = this.frame;
                    }
                    else
                    {
                        if (path.ToLower().EndsWith(".html"))
                        {
                            path = path.Substring(0, path.Length - 5) + ".md";
                        }

                        if (System.IO.File.Exists(path))
                        {
                            var mdfi = new System.IO.FileInfo(path);
                            var editor = new MarkdownEditor(mdfi.Name, false, false, false, false, false, false, true, true, MarkdownEditorBase.HighlightingType.Advance);
                            editor.HorizontalAlignment = HorizontalAlignment.Stretch;
                            editor.VerticalAlignment = VerticalAlignment.Stretch;
                            editor.EditorBase.IsReadOnly = true;
                            editor.OpenDocument(path);
                            editor.FontSize = 36;
                            editor.FontFamily = Globals.MainWindow.FontFamily;

                            var tabControl = new BetterWpfControls.TabControl();
                            tabControl.TabStripPlacement = Dock.Bottom;
                            tabControl.Items.Add(editor);
                            this.Content = tabControl;
                        }
                    }
                }
                else
                {
                    var lastIndexOfDot = htmlpath.LastIndexOf(".");
                    if (lastIndexOfDot == -1 || htmlpath.EndsWith("."))
                    {
                        this.image = new Image();
                        this.image.Source = Globals.LoadBitmapImageFromFile(path);
                        this.Content = this.image;
                    }
                    else
                    {
                        var extenssion = htmlpath.Substring(lastIndexOfDot + 1);
                        if(string.IsNullOrEmpty(extenssion))
                        {
                            this.image = new Image();
                            this.image.Source = Globals.LoadBitmapImageFromFile(path);
                            this.Content = this.image;
                        }
                        else
                        {
                            switch (extenssion.ToLower())
                            {
                                case "bmp":
                                case "ico":
                                case "png":
                                case "gif":
                                case "jpg":
                                case "jpeg":
                                case "tiff":
                                    {
                                        this.image = new Image();
                                        this.image.Source = Globals.LoadBitmapImageFromFile(path);
                                        this.Content = this.image;
                                        break;
                                    }
                                case "mp3":
                                case "wav":
                                case "wma":
                                case "mp4":
                                    {
                                        this.player = new LMediaPlayer()
                                        {
                                            HorizontalAlignment = HorizontalAlignment.Stretch,
                                            VerticalAlignment = VerticalAlignment.Stretch,
                                        };

                                        this.player.Source = new Uri(path);
                                        this.Content = this.player;
                                        break;
                                    }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LMessageBox.ShowWarning(ex.Message);
            }

            this.Closing += DemoResourceCard_Closing;
            this.Closed += DemoResourceCard_Closed;
            this.PreviewMouseLeftButtonDown += DemoResourceCard_PreviewMouseLeftButtonDown;
            this.KeyDown += DemoResourceCard_KeyDown;

            this.Activated += DemoResourceCard_Activated;
            this.SizeChanged += DemoResourceCard_SizeChanged;
           
        }

        private void DemoResourceCard_Closed(object sender, EventArgs e)
        {
            if(this.player != null)
            {
                this.player.Pause();
            }
        }

        private void DemoResourceCard_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Escape)
                this.Close();
        }

        private void DemoResourceCard_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                var demoWin = Window.GetWindow(this.MasterResourceButton) as GraphicDemonstrator;
                if (demoWin != null)
                {
                    if (demoWin is GraphicDemonstrator gwin)
                    {
                        var leftTop = demoWin.mainCanvas.PointToScreen(new Point(0, 0));
                        //var rightBottom = this.mainCanvas.PointToScreen(new Point(this.mainCanvas.ActualWidth, this.mainCanvas.ActualHeight));

                        this.Width = gwin.mainCanvas.ActualWidth;
                        this.Height = gwin.mainCanvas.ActualHeight;

                        this.WindowState = WindowState.Normal;
                        this.Left = leftTop.X;
                        this.Top = leftTop.Y;
                    }
                }
            }
            else if (this.WindowState == WindowState.Minimized)
            {
                this.MasterResourceButton.IsChecked = false;
            }
        }

        private void DemoResourceCard_Activated(object sender, EventArgs e)
        {
            if (this.Owner is GraphicDemonstrator gWin)
            {
                gWin.ActivedCard = this;
            }
        }

        private void DemoResourceCard_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Visibility = System.Windows.Visibility.Collapsed;
            this.MasterResourceButton.IsChecked = false;

            this.MasterResourceButton.SwitchLayoutPanels();

            if (this.Owner != null)
            {
                var wins = this.Owner.OwnedWindows;
                if (wins != null && wins.Count > 0)
                {
                    var index = 0;
                    for (int i = 0; i < wins.Count; i++)
                    {
                        var win = wins[i];
                        if (win == this)
                        {
                            index = i;
                            break;
                        }
                    }

                    if (index >= 1)
                    {
                        wins[index - 1].Activate();
                    }
                }
            }

            if(this.player != null)
            {
                this.player.Pause();
            }
        }

        private void DemoResourceCard_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                if (this.WindowState == WindowState.Maximized)
                {
                    this.WindowState = WindowState.Normal;
                }
                else
                {
                    this.WindowState = WindowState.Maximized;
                }
            }
        }

        private Frame frame;

        private Image image;

        private LMediaPlayer player;

        public LMediaPlayer Player
        {
            get { return this.player; }
        }

        private DemoResourceButton masterResourceButton;

        public DemoResourceButton MasterResourceButton { get { return this.masterResourceButton; } }
    }
}
